How it all works

In the diagramf package, TEX and METAFONT communicate by auxiliary files, in a similar fashion to the MG TEX- interface (`Problems on the TEX//graphics interface', 11(3)).

When you run METAFONT on dmfexmpl.mf it reads in dmfexmpl.dim, which specifies the dimensions of all the boxes. In our example, part of dmfexmpl.dim is

wd#[2][0] := 20.3344pt#;
ht#[2][0] := 6.94444pt#;
dp#[2][0] := 1.94444pt#;
So, in diagram 2, label 0 has width 20.3344pt, height 6.94444pt and depth 1.94444pt. From this, METAFONT calculates where to put each label, and outputs a .dia file, containing TEX code. For example dmfexmpl.dia contains[*]:
\newdiagram{2}
\diagramlabel{0}{4.88908pt}{0pt}
$g \circ h$
\enddiagramlabel
\diagramchar{2}
\endnewdiagram
This tells TEX that diagram number 2 contains label 0 at coordinates (4.88908pt, 0pt) consisting of $g \circ h$. The diagram is character number 2 in the dmfexmpl font.

Similarly, when TEX encounters the instruction \diagramfile{dmfexmpl} it loads in dmfexmpl.dia and produces dmfexmpl.dim. And so we can have our METAFONT cake and eat it in TEX.

Well, almost. Unfortunately for all these grand ideas, METAFONT has no file-handling capabilities at all! The only files METAFONT generates are the .tfm, .gf and .log files.

This is rather annoying, but fortunately we can steal an idea from Section 7 of the Dirty Tricks appendix in . There, Knuth uses the .log file as a means of communicating between METAFONT jobs. Similarly, we use the .log file as a way of sending messages to TEX. Our texoutput macro is defined

def texoutput text t =
    for s = t:
        message s & "% diagramf";
    endfor
    message ""
enddef;
So texoutput "Fred", "Ethel" produces the output
Fred% diagramf
Ethel% diagramf
You can then use your favourite file-handling utility to filter the .log file, keeping only the lines containing % diagramf. On my UNIX set-up, for example, I have an alias diagramf foo which expands out to
touch foo.dim
mf foo
grep "% diagramf" foo.log > foo.dia
echo Labels written on foo.dia.
The crucial line in this is the grep, which takes all the lines from foo.log containing % diagramf and puts them in foo.dia.

And so we've achieved labelled diagrams in METAFONT. The diagramf package is free software, and is available from the Aston archive.